import React, { Component } from 'react';
import { connect } from 'dva';
import { Input, Tooltip ,Icon} from 'antd';
import PropTypes from 'prop-types';
const defaultProps = {
  icon:'',
  num:0,
}
const propTypes = {
  icon:PropTypes.string,
  num:PropTypes.number
}
function formatNumber(value) {
  value += '';
  const list = value.split('.');
  const prefix = list[0].charAt(0) === '-' ? '-' : '';
  let num = prefix ? list[0].slice(1) : list[0];
  let result = '';
  while (num.length > 3) {
    result = `,${num.slice(-3)}${result}`;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
}

class NumericInput extends React.Component {
  constructor(props){
    super(props);
    this.state={
      icon:this.props.icon
    }
  }
  onChange = (e) => {
    const { value } = e.target;
    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
    if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
      this.props.onChange(value);
    }
  }
  // '.' at the end or only '-' in the input box.
  onBlur = () => {
    const { value, onBlur, onChange } = this.props;
    if (value.charAt(value.length - 1) === '.' || value === '-') {
      onChange({ value: value.slice(0, -1) });
    }
    if (onBlur) {
      onBlur();
    }
  }
  render() {
    const { value ,icon} = this.props;
    const title = value ? (
      <span className="numeric-input-title">
        {value !== '-' ? formatNumber(value) : '-'}
      </span>
    ) : 'Input a number';
    return (
        <Input
        className={this.props.className}
          {...this.props}
          onChange={this.onChange}
          onBlur={this.onBlur}
          prefix={<Icon type={icon} style={{ fontSize: 14 }} />}
          placeholder={this.props.placeholder}
          maxLength="25"
        />
    );
  }
}

class NumericInputDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }
  onChange = (value) => {
    this.setState({ value });
  }
  render() {
    return <NumericInput icon={this.props.icon} className={this.props.className} placeholder={this.props.placeholder} value={this.state.value} onChange={this.onChange} />;
  }
}
NumericInputDemo.defaultProps=defaultProps;
NumericInputDemo.PropTypes=propTypes;
export default NumericInputDemo;